
// 发送get请求
function get(url, params, headers = {})
{
    const p = new Promise((resolve, reject)=>{
        // 1,创建xhr对象
        const xhr =new XMLHttpRequest
        // 2,设置请求方式，请求地址
        let temp =[]
        for (let key in params){
            temp.push(`${key}=${params[key]}`)
        }
        xhr.open('get',`${url}?${temp.join('&')}`)
        // 3,监控请求状态
       xhr.onreadystatechange = ()=>{
        if(xhr.readyState ===4)
        if(xhr.status ===200)
        {
            let res = JSON.parse(xhr.responseText)
            resolve(res)
        }else{
            reject(xhr.status)
        }
       }

    //    4,发送请求
    for(let key in headers){
        xhr.setRequestHeader(key,headers[key])
    }
    xhr.send()
    })
}

// 发送post请求
function post(url,params,headers={})
{
    const p =new Promise((resolve,reject)=>{
        const xhr = new XMLHttpRequest

        xhr.open('post',url)
        xhr.onreadystatechange = ()=>{
            if(xhr.readyState ===4)
            {
                if(xhr.status ===200)
                {
                    let res =JSON.parse(xhr.responseText)
                    resolve(res)
                }else{
                    reject(xhr.status)
                }
            }
        }
        
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
        for(let key in headers){
            xhr.setRequestHeader(key,headers[key])
        }
        let temp = []
        for (let key in params) {
            temp.push(`${key}=${params[key]}`)
        }
        xhr.send(temp.join('&'))
    })
    return p
}